/**
 * search_page & search_result_page 待改进
 * 这里的问题很大，搜索结果页面不应该使用一整个组件渲染返回，而是动态ListView 只需响应数据的变化、
 * 该实现性能很差，待改进
 */

import 'package:flutter/material.dart';
import 'package:wanandroid_flutter/api/common_service.dart';

import 'package:wanandroid_flutter/model/hotword_model.dart';
import 'package:wanandroid_flutter/components/search_hotword_widget.dart';
import 'package:wanandroid_flutter/ui/search_result_page.dart';

class SearchPage extends StatefulWidget {
  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  String _inputValue;
  TextEditingController textEditingController;
  List<Widget> hotkeyWidgets = List();
  FocusNode focusNode = FocusNode();
  SearchResultPage _searchResultPage;

  @override
  void initState() {
    super.initState();
    textEditingController = TextEditingController(text: _inputValue);
    _getHotKey();
  }

  @override
  void dispose() {
    textEditingController.dispose();
    super.dispose();
  }

  /// ==========================================================

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: _textField(context),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.search),
            onPressed: _searchIconPressed,
          ),
          IconButton(
            icon: Icon(Icons.close),
            onPressed: () {
              setState(() {
                textEditingController.clear();
              });
            },
          ),
        ],
      ),
      body: (textEditingController.text == null ||
              textEditingController.text.isEmpty)
          ? SearchHotwordPage(hotkeyWidgets: hotkeyWidgets)
          : _searchResultPage,
    );
  }

  Widget _textField(BuildContext context) {
    return TextField(
      autofocus: true,
      decoration: InputDecoration(
        border: InputBorder.none,
        hintText: '搜索关键词',
        hintStyle: TextStyle(color: Colors.white70),
      ),
      controller: textEditingController,
      style: TextStyle(color: Colors.white),
      focusNode: focusNode,
    );
  }

  /// =====================================
  Future<Null> _getHotKey() async {
    CommonService().getSearchHotWord((HotWordModel hotWordModel) {
      setState(() {
        List<HotWordData> datas = hotWordModel.data;
        hotkeyWidgets.clear();

        for (var value in datas) {
          hotkeyWidgets.add(ActionChip(
            label: Text(value.name),
            onPressed: () {
              setState(() {
                textEditingController.text = value.name;
              });
              _searchIconPressed();
            },
          ));
        }
      });
    });
  }

  void _searchIconPressed() {
    focusNode.unfocus();
    setState(() {
      _searchResultPage =
          SearchResultPage(ValueKey(textEditingController.text));
    });
  }
}
